import { Utils } from 'tuya-panel-kit';
import _throttle from 'lodash/throttle';
import _debounce from 'lodash/debounce';
import TYSdk from '../api';
import Strings from '../i18n';

const { NumberUtils } = Utils;

// 判断是否是中文
const isChinese = (str) => {
  let lst = /[u00-uFF]/;
  return !lst.test(str);
};

// 中英文混合计算字符长度
export const strlen = (str) => {
  let strlength = 0;
  for (let i = 0; i < str.length; ++i) {
    if (isChinese(str.charAt(i)) == true)
      strlength = strlength + 2; //中文计算为2个字符
    else
      strlength = strlength + 1; //中文计算为1个字符
  }
  return strlength;
};

export const arrayToObject = arr => {
  if (arr.length === 0) {
    return {};
  }
  return Object.assign(...arr);
};

export const getFaultString = (faultCode, faultValue, onlyPrior = true) => {
  if (!faultValue) return '';
  const { label } = TYSdk.device.getDpSchema(faultCode);
  const labels = [];
  for (let i = 0; i < label.length; i++) {
    const value = label[i];
    const isExist = NumberUtils.getBitValue(faultValue, i);
    if (isExist) {
      labels.push(Strings.getDpLang(faultCode, value));
      if (onlyPrior) break;
    }
  }
  return onlyPrior ? labels[0] : labels.join(', ');
};

/**
 * 节流函数
 * 回调方法执行时，会以当前最新的数据来执行，即若在回调方法未被执行前，连续调用了节流函数，则在节流时间到达后，会以最新的数据执行回调方法
 * @param {function} callback 回调方法
 * @param {*} waitTime 节流时间
 */
const throttle = (callback, waitTime = 300) => _throttle(callback, waitTime);

const debounce = (callback, waitTime = 300) => _debounce(callback, waitTime);

export { throttle, debounce };
